#include "callroll.h"
#include "ui_callroll.h"

CallRoll::CallRoll(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CallRoll)
{
    ui->setupUi(this);

    ui->labelName->installEventFilter(this);
    ui->pushButtonStop->setDisabled(true);

    connect(ui->pushButtonCall,&QPushButton::clicked,this,&CallRoll::startCall);
    connect(ui->pushButtonStop,&QPushButton::clicked,[=](){
        tim.stop();
    });
}

void CallRoll::startCall(){
    if(namesFile.isNull()){
        QMessageBox::critical(this,tr("Error!"),tr("No name file loaded!\n"
                                                   "Please click the blank space "
                                                   "at the top to load a name file"));
        return;
    }
    ui->pushButtonStop->setEnabled(true);
    QFile namef(namesFile);
    if (!namef.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    QTextStream nameStream(&namef);
    nameStream.setCodec("UTF-8");
    QStringList names;
    while (!nameStream.atEnd()) {
        names.append(nameStream.readLine().remove("\n"));
    }
    namef.close();

    connect(&tim,&QTimer::timeout,this,[=](){
        int i=QRandomGenerator::global()->bounded(0,names.length());
     QFont font ( "MicroSoft YaHei",20, 50);
     ui->labelName->setFont(font);
          ui->labelName->setText(names[i]);
    });

    tim.start(100);
}
void CallRoll::getNamesFile(){
    if(namesFile.isNull()){
        namesFile=QFileDialog::getOpenFileName(this,tr("Open the Names File"),
                                               "./",
                                               tr("text File(*.txt *.csv)"));
    }else {
        QMessageBox::StandardButton rb = QMessageBox::question(NULL, tr("Question"), "Do you want to load a new Names File?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        if(rb==QMessageBox::Yes)
        {
            namesFile=QFileDialog::getOpenFileName(this,tr("Open the Names File."),
                                                   "/",
                                                   tr("text File(*.txt *.csv)"));
        }
    }
}
bool CallRoll::eventFilter(QObject *obj, QEvent *event){
    if(obj!=ui->labelName||event->type()!=QEvent::MouseButtonPress)
        return false;
    QMouseEvent *mevent=static_cast<QMouseEvent*>(event);
    if(mevent->button()==Qt::LeftButton)
        getNamesFile();
    return true;
}


CallRoll::~CallRoll()
{
    delete ui;
}
